package tank02;

import javax.swing.*;
import java.awt.*;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;

/**
 * 游戏面板
 */
public class MyPanel extends JPanel implements KeyListener,Runnable {

    //创建英雄坦克对象
    private Hero hero = new Hero(10,10, Color.CYAN);

    //重写绘制方法
    @Override
    public void paint(Graphics e ) {
        super.paint(e);
        //填充游戏背景界面
        e.setColor(Color.BLACK);
        e.fillRect(0,0,600,800);
        //绘制坦克
        hero.draw(e);
    }

    //实现按键事件
    @Override
    public void keyPressed(KeyEvent e) {
        //判断玩家的按键
        switch (e.getKeyCode()) {
            case KeyEvent.VK_UP:
                //修改坦克方向为上
                hero.setDirection(Tank.DIRECTION_UP);
                break;
            case KeyEvent.VK_DOWN:
                hero.setDirection(Tank.DIRECTION_DOWN);
                break;
            case KeyEvent.VK_LEFT:
                hero.setDirection(Tank.DIRECTION_LEFT);
                break;
            case KeyEvent.VK_RIGHT:
                hero.setDirection(Tank.DIRECTION_RIGHT);
                break;
        }

    }
    @Override
            public void run() {
        while (true){
        //玩家坦克移动
        hero.move();
        //重绘面板
        repaint();
        //睡眠100秒
            try {
                Thread.sleep(100);
            }catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
        }
    }


    @Override
    public void keyTyped(KeyEvent e) {

    }

    @Override
    public void keyReleased(KeyEvent e) {

    }
}